package com.choosefine.base.shixiaobao.base;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.choosefine.base.shixiaobao.base.dto.DateDTO;
import com.choosefine.base.shixiaobao.base.dto.IdentityDTO;
import com.choosefine.base.shixiaobao.common.def.ResultCode;
import com.choosefine.base.shixiaobao.common.json.JsonDataResult;
import com.choosefine.base.shixiaobao.common.json.JsonResult;
import com.choosefine.base.shixiaobao.common.model.CustomRestTemplate;
import com.choosefine.base.shixiaobao.common.utils.MessageSourceUtils;
import com.github.pagehelper.Page;

/**
 * 控制层的共性
 * 
 * @auth liaozhanggen 2016-11-19 上午9:42:30
 * 
 */
public class BaseController {

	public CustomRestTemplate customRestTemplate = new CustomRestTemplate();

	private Logger logger = LoggerFactory.getLogger(BaseController.class);

	@Value("#{yaml.get('service.shixiaobao.url')}")
	public String shixiaobaoURL;

	@Value("#{yaml.get('service.shopping.url')}")
	public String shoppingURL;

	@Value("#{yaml.get('service.usercent.url')}")
	public String usercentURL;

	@Value("#{yaml.get('service.push.url')}")
	public String pushURL;

	@Value("#{yaml.get('service.communication.url')}")
	public String communicationURL=null;

	protected final static String DATE_FORMATE = "yyyy-MM-dd";
	private JsonResult result = null;

	@Autowired
	public MessageSourceUtils messageSourceUtils; // 国际化读取key/value

	/**
	 * @param data
	 *            返回的展示数据 json 对象
	 * @param MESSAGE
	 *            返回的成功或失败的原因 比如：SUCCESS / ERROR ....
	 * @param resultCode
	 *            返回的成功或失败的编码 比如：200、 500、400....
	 * 
	 * @auth liaozhanggen 2016-11-19 上午10:14:42
	 */
	public JsonResult responseSuccess(Object data, String MESSAGE, Integer resultCode) {
		logger.info("--------------getInstanceJsonResult--------------> new");
		result = new JsonResult(data, MESSAGE, resultCode);
		return result;
	}

	public String responseSuccess() {
		this.responseSuccess(null, ResultCode.MSG_SUCCESS, ResultCode.SUCCESS);
		return result.toJson();
	}

	public String responseSuccess(Object data) {
		logger.info("后端返回对象：{}", data);
		if (data instanceof Page) {
			JsonDataResult<Object> jdr = new JsonDataResult<>();
			jdr.setList((Page) data);
			jdr.setPages(((Page) data).toPageInfo().getPages());
			jdr.setTotal(((Page) data).toPageInfo().getTotal());
			jdr.setPageSize(((Page) data).toPageInfo().getPageSize());
			jdr.setPageNum(((Page) data).toPageInfo().getPageNum());
			this.responseSuccess(jdr, ResultCode.MSG_SUCCESS, ResultCode.SUCCESS);
		} else {
			this.responseSuccess(data, ResultCode.MSG_SUCCESS, ResultCode.SUCCESS);
		}
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseSuccess(Object data, String MESSAGE) {
		logger.info("后端返回对象：{}", data);
		result = new JsonResult(data, MESSAGE, ResultCode.SUCCESS);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseSuccess(Object data, Integer resultCode, String MESSAGE) {
		logger.info("后端返回对象：{}", data);
		result = new JsonResult(data, MESSAGE, resultCode);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseFail() {
		result = new JsonResult(ResultCode.MSG_ERROR, ResultCode.FAILED);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseFail(String MESSAGE) {
		result = new JsonResult(MESSAGE, ResultCode.FAILED);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	public String responseFail(Object data, String faileMsg) {
		result = new JsonResult(data, faileMsg, ResultCode.FAILED);
		return result.toJson();
	}

	public String responseFail(Object data) {
		result = new JsonResult(data, ResultCode.MSG_ERROR, ResultCode.FAILED);
		return result.toJson();
	}

	public String responseFail(Integer resultCode, String MESSAGE) {
		result = new JsonResult(MESSAGE, resultCode);
		logger.info("后端返回数据：" + result.toJson());
		return result.toJson();
	}

	/**
	 * 11.29dzq 用于输入时间判断。
	 * 
	 * @return 返回时间是否合法
	 */
	public boolean timeJudge(long startTime, long endTime) {
		if ((startTime == 0 && endTime == 0)|| endTime == 0) {
			endTime = System.currentTimeMillis(); // 取当前时间
		}
		if (startTime >= endTime || startTime < 0){
			return false;
		}
		return true;
	}

	/**
	 * 12.7 dzq 时间验证，需配合datedto
	 * 
	 * @return
	 */
	public boolean timeJudge(DateDTO date) {
		if (date == null) {
			return false;
		}
		if (date.getStartTime() == 0 && date.getEndTime() == 0) {
			date.setEndTime(System.currentTimeMillis());
		}
		if (date.getEndTime() == 0) {// 如果结束时间为0
			date.setEndTime(System.currentTimeMillis());// 取当前时间
		}
		if (date.getStartTime() >= date.getEndTime() || date.getStartTime() < 0)
			return false;
		return true;
	}

//	/**
//	 * 请求身份验证
//	 * 
//	 * @param identity
//	 * @return
//	 */
//	public boolean identityVerification(ShoppingIdentityDTO identity) {
//		if (identity == null) {
//			return false;
//		}
//		if ((identity.getTeamId() == null || "".equals(identity.getTeamId()))
//				&& (identity.getProjectCode() == null || "".equals(identity.getProjectCode()))
//				&& (identity.getUserCode() == null || "".equals(identity.getUserCode()))) {
//			return false;
//		}
//		return true;
//	}

//	/**
//	 * 参数map添加用户与时间
//	 * 
//	 * @param param
//	 * @param date
//	 * @param identity
//	 */
//	public Map<String, Object> fomartMap(Map<String, Object> param, DateDTO date, ShoppingIdentityDTO identity) {
//		if (param != null){
//			Iterator<String> ite = param.keySet().iterator();
//			while (ite.hasNext()) {
//				Object now = ite.next();
//				if ("-1".equals(param.get(now.toString()).toString())) {
//					param.remove(now.toString());
//				}
//			}
//			if (identity != null) {// 身份
//				param.put("userCode", identity.getUserCode());
//				param.put("projectCode", identity.getProjectCode());
//				param.put("teamId", identity.getTeamId());
//			}
//			if (date != null) {
//				param.put("startTime", date.getStartTime());
//				param.put("endTime", date.getEndTime());
//			}
//		}
//		return param;
//	}

	/**
	 * 请求身份验证
	 * 
	 * @param identity
	 * @return
	 */
	public boolean identityVerification(IdentityDTO identity) {
		if (identity == null) {
			return false;
		}
		if ((identity.getTeamId() == null || "".equals(identity.getTeamId()))
				&& (identity.getProjectCode() == null || "".equals(identity.getProjectCode()))
				&& (identity.getUserCode() == null || "".equals(identity.getUserCode()))) {
			return false;
		}
		return true;
	}

	/**
	 * 参数map添加用户与时间
	 * 
	 * @param param
	 * @param date
	 * @param identity
	 */
	public Map<String, Object> fomartMap(Map<String, Object> param, DateDTO date, IdentityDTO identity) {
		if (param != null){
			Iterator<String> ite = param.keySet().iterator();
			while (ite.hasNext()) {
				Object now = ite.next();
				if ("-1".equals(param.get(now.toString()).toString())) {
					param.remove(now.toString());
				}
			}
			if (identity != null) {// 身份
				param.put("userCode", identity.getUserCode());
				param.put("projectCode", identity.getProjectCode());
				param.put("teamId", identity.getTeamId());
			}
			if (date != null) {
				param.put("startTime", date.getStartTime());
				param.put("endTime", date.getEndTime());
			}
		}
		return param;
	}

	/**
	 * 12.13dzq 增加时间方法，为前端提供当前页面可选时间段
	 * 
	 * @return
	 */
	@Deprecated
	public static List<String> timeList(long startTime, long endTime, List<String> list) {
		if (list != null){
			SimpleDateFormat sf = new SimpleDateFormat(" ");
			int n = 0;
			Calendar c1 = Calendar.getInstance();
			Calendar c2 = Calendar.getInstance();
			c1.setTimeInMillis(startTime);
			c2.setTimeInMillis(endTime == 0 ? System.currentTimeMillis() : endTime);
			while (!c1.after(c2)) {
				if (n == 0) {
					list.add(sf.format(c1.getTime()));
				} else {
					c1.add(Calendar.MONTH, 1);
					list.add(sf.format(c1.getTime()));
				}
				n++;
			}
			list.remove(n - 1);
		}
		return list;
	}

}
